<template>
  <div class="upload-demo">
    <el-upload
      action="/api/files/upload"
      :with-credentials="true"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-success="handleAvatarSuccess"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">单文件上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传 jpg、png、gif 文件，且不超过 200kb </div>
    </el-upload>

    <br>
    <br>
    <br>
    <br>

    <el-upload
      action="/api/files/upload"
      :with-credentials="true"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="3"
      :auto-upload="false"
      :on-change="handleFilesChange"
      :on-success="handleAvatarSuccess"
      :on-exceed="handleExceed"
      :file-list="fileListBatch"
    >
      <el-button size="small" type="primary">选择文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传 jpg、png、gif 文件，且不超过 200kb </div>
    </el-upload>
    <el-button size="small" type="primary" @click="uploadBatch">多文件上传</el-button>
  </div>
</template>
<script>
import { uploadBatch } from '@/api/files'

export default {
  data() {
    return {
      fileList: [],
      fileListBatch: []
    }
  },
  methods: {
    // 多文件上传
    uploadBatch() {
      if (this.fileListBatch.length) {
        const formData = new FormData()
        formData.append('username', '张三')
        for (const item of this.fileListBatch) {
          formData.append('files', item.raw)
        }
        uploadBatch(formData).then(({ code }) => {
          if (code === 20000) {
            this.$message.success(`文件上传成功！`)
          }
        })
      } else {
        this.$message.warning(`请上传文件！`)
      }
    },
    handleFilesChange(file, fileList) {
      this.fileListBatch = fileList
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 10000) {
        this.$message.error(res.message)
        this.fileList.splice(this.fileList.length, 1)
      } else {
        this.$message.success('上传成功')
      }
    },
    handleRemove(file, fileList) {
      this.fileListBatch = fileList
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-demo {
  text-align: center;
  margin-top: 100px;
}
</style>
